import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getStuList, deleteStuByIdApi, addStuApi } from '../api/stuApi';


// 获取数据  createAsyncThunk 的第一个参数可以很随意 不影响大局 但是也有默认的规范
export const getStu = createAsyncThunk('stu/getStu', async (_, { dispatch }) => {
    const res = await getStuList()
    dispatch(initStu(res.data))
})

// 删除数据
export const deleteStu = createAsyncThunk('stu/delete', async (pro, { dispatch }) => {
    await deleteStuByIdApi(pro)
    dispatch(delStu(pro))
})

// 新增
export const addStuApiItem = createAsyncThunk('stu/add', async (payload, { dispatch }) => {
    await addStuApi(payload)

    dispatch(addStu(payload))
})

const stuSplice = createSlice({
    name: "stu",
    initialState: {
        stuList: [

        ]
    },
    reducers: {
        initStu: (state, { payload }) => {
            state.stuList = payload;
        },
        addStu: (state, { payload }) => {
            state.stuList.push(payload)
        },
        delStu: (state, { payload }) => {
            state.stuList = state.stuList.filter(item => item.id !== payload)
        }
    }
})

export default stuSplice.reducer
export const { addStu, delStu, initStu } = stuSplice.actions